package zsc.ruanc.practicaltraining.security.components;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import zsc.ruanc.practicaltraining.mapper.UrlMapper;
import zsc.ruanc.practicaltraining.model.domain.TUrl;
import zsc.ruanc.practicaltraining.security.auth.AuthUser;
import zsc.ruanc.practicaltraining.security.exception.SAccessDeniedException;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

@Component
public class UrlJudge {

    @Autowired
    private UrlMapper urlMapper;

    public boolean check(HttpServletRequest request,
                         Authentication authentication) throws SAccessDeniedException {

        Object principal = authentication.getPrincipal();

        System.out.println("开始判权");
        System.out.println("DynamicPermission principal = " + principal);

        if (principal instanceof AuthUser) {


            String requestURI = request.getRequestURI();
            AntPathMatcher antPathMatcher = new AntPathMatcher();

            System.out.println("请求的url：" + requestURI);

            List<TUrl> urlList = urlMapper.select(1);

            for (TUrl item : urlList) {
                if (antPathMatcher.match(item.getUrl(), requestURI)) {
                    String role = (String) request.getAttribute("role");
                    if (!role.equals("ROLE_admin")) {
                        throw  new SAccessDeniedException("您没有访问该API的权限！");
                    } else {
                        return true;
                    }
                }
            }



        }
        return true;
    }

}
